package com.ac.scum.log.web.model.wechat.mp.handler;

import com.ac.scum.log.web.model.wechat.mp.builder.TextBuilder;
import com.ac.scum.log.web.model.wechat.mp.mapper.WeChatUserMapper;
import com.ac.scum.wechat.bean.WeChatUser;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Map;

/**
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@Slf4j
@Component
@AllArgsConstructor
public class SubscribeHandler extends AbstractHandler {
    private final WeChatUserMapper weChatUserMapper;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) throws WxErrorException {
        boolean isNewUser = false;
        log.info("新关注用户 OPENID: " + wxMessage.getFromUser());
        WeChatUser weChatUser = weChatUserMapper.selectByOpenId(wxMessage.getFromUser());
        if (weChatUser == null) {
            isNewUser = true;
            weChatUser = new WeChatUser();
        }
        try {
            WxMpUser userWxInfo = weixinService.getUserService().userInfo(wxMessage.getFromUser(), null);
            if (userWxInfo != null) {
                weChatUser.setSubscribeTime(LocalDateTime.ofInstant(Instant.ofEpochMilli(userWxInfo.getSubscribeTime() * 1000), ZoneId.systemDefault()));
                weChatUser.setOpenId(userWxInfo.getOpenId());
                weChatUser.setIsSubscribe(true);
                weChatUser.setLanguage(userWxInfo.getLanguage());
                weChatUser.setGroupId(userWxInfo.getGroupId());
            }
        } catch (WxErrorException e) {
            if (e.getError().getErrorCode() == 48001) {
                log.info("该公众号没有获取用户信息权限！");
            }
        }
        if (isNewUser) {
            weChatUserMapper.insert(weChatUser);
        } else
            weChatUserMapper.update(weChatUser, Wrappers.lambdaUpdate(WeChatUser.class).eq(WeChatUser::getOpenId, weChatUser.getOpenId()));


        try {
            return new TextBuilder().build("感谢关注", wxMessage, weixinService);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return null;
    }
}
